package mwa.cs.rq.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mwa.cs.dao.AddressDAO;
import mwa.cs.dao.RequestDAO;
import mwa.cs.dao.RequestQuoteDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.database.Database;
import mwa.cs.model.Ar;
import mwa.cs.model.Request;
import mwa.cs.util.JDate;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * Servlet implementation class CS64000Srvl
 */
public class CS64000Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaAgentBrowser;
	private String vaUrlAddress;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS64000Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }

    @SuppressWarnings({ "unchecked", "unused" })
	public void processRequest(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
    	
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());

		vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
    	request.setCharacterEncoding("UTF-8");
   		response.setCharacterEncoding("UTF-8");
   		response.setContentType("text/JSON");
   		String vaProcessType = request.getParameter("methodType");
		if (vaProcessType.equals("getData")){
			getData(request, response);
		} else {
			saveData(request, response);
		}
	}
    
    @SuppressWarnings("unchecked")
	public void saveData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
		Request voRequest = new Request();
    	RequestDAO voRequestDAO = new RequestDAO(db);
		String vaChooseRequest = request.getParameter("chooseRequest").trim();
		String vaRequestNumber = request.getParameter("requestNumber").trim();
		String vaDescription = request.getParameter("description").trim();
		String vaReason = request.getParameter("reason").trim();
		String vaStatus = "";
		String vaReasonCancel = "";
		String vaReasonClose = "";
		if (vaChooseRequest.equals("0")) {
			vaReasonClose = vaReason;
			vaStatus = "3";
		} else {
			vaReasonCancel = vaReason;
			vaStatus = "4";
		}
		int updateUserId = 1; //(Integer) request.getSession().getAttribute("user_id");
		String updateDate = JDate.getDate();
		String updateTime = JDate.getTime();
		
		voRequest.setVaDescription(vaDescription);
		voRequest.setVaStatus(vaStatus);
		voRequest.setVaReasonClose(vaReasonClose);
		voRequest.setVaReasonCancel(vaReasonCancel);
		voRequest.setVnUpdateUserId(updateUserId);
		voRequest.setVaUpdateDate(updateDate);
		voRequest.setVaUpdateTime(updateTime);
		voRequest.setVaRequestNumber(vaRequestNumber);
		try {
			db.beginTransaction();
			boolean vbResult = voRequestDAO.updateRequestForCloseOrCancel(voRequest);
			if (vbResult) {
				voObject.put("chooseRequest", vaChooseRequest);
				voObject.put("message", "success");
				db.commit();
			} else {
				voObject.put("chooseRequest", vaChooseRequest);
				voObject.put("message", "fail");
			}
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS64000", JDate.getDate(), JDate.getTime(),vnUserId, "CS64000Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			db.rollback();
			voObject.put("chooseRequest", vaChooseRequest);
			voObject.put("message", "fail");
		}
		db.close();
		voOut.print(voObject.toJSONString());
    }
    
    @SuppressWarnings("unchecked")
	public void getData(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	PrintWriter voOut = response.getWriter();
		JSONObject voObject = new JSONObject();
		Database db = new Database();
    	RequestDAO voRequestDAO = new RequestDAO(db);
    	RequestQuoteDAO voRequestQuoteDAO = new RequestQuoteDAO(db);
    	AddressDAO voAddressDAO = new AddressDAO(db);
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());

		String vaChooseRequest = request.getParameter("chooseRequest");
		String vaInputRequestNumber = request.getParameter("inputRequestNumber");
		String vaRequestNumber = "";
		String vaApplicantName = "";
		String vaHomeNumber = "";
		String vaAddress = "";
		String vaCity = "";
		String vaDistrict = "";
		String vaProvince = "";
		String vaPostCode = "";
		String vaTelephone = "";
		String vaRequestDescription = "";
		String vaRequestGroup = "";
		String vaRequestType = "";
		JSONArray voReceiveCode = new JSONArray();
		JSONArray voDescription = new JSONArray();
		JSONArray voReceiveAmount = new JSONArray();
		
		List<Map<String, Object>> voArrayList = null;
		Map<String, Object> voMapRequest = new HashMap<String, Object>();
		Map<String, Object> voMapRequestQuote = new HashMap<String, Object>();
		voMapRequest = voRequestDAO.getRequestForCloseOrCancel(vnSiteId, vaInputRequestNumber);
		voArrayList = voRequestQuoteDAO.searchRequestQuote(vnSiteId, vaInputRequestNumber);
		if (voMapRequest == null) {
			voObject.put("message", "resultNull");
		} else {
			if (vaChooseRequest.equals("0")) {
				vaRequestGroup = ""+ voMapRequest.get("REQUEST_GROUP");
				vaRequestType = ""+ voMapRequest.get("REQUEST_TYPE");
				if (vaRequestType.equals("01") && vaRequestGroup.equals("0")) {
					
					voObject.put("message", "resultNull");
				} else {
				
					if (voArrayList.size() != 0 && voMapRequest.get("STATUS").toString().equals("1")) {
			    		voObject.put("message", "resultNull");
			    	} else {
			    		for (int i = 0; i < voArrayList.size(); i++) {
			    			voMapRequestQuote = voArrayList.get(i);	
			    			voReceiveCode.add(voMapRequestQuote.get("RECEIVE_CODE"));
							voDescription.add(voMapRequestQuote.get("DESCRIPTION"));
							voReceiveAmount.add(voMapRequestQuote.get("RECEIVE_AMOUNT"));
						}
			    		
			    		vaRequestNumber = ""+ voMapRequest.get("REQUEST_NUMBER");
				    	vaApplicantName = ""+ voMapRequest.get("APPLICANT_NAME");
				    	vaHomeNumber = ""+ voMapRequest.get("CONTACT_HOME_NUMBER");
				    	vaAddress = "" + voMapRequest.get("CONTACT_ADDRESS");
				    	vaCity = voAddressDAO.getCityName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"), ""+ voMapRequest.get("CONTACT_DISTRICT_CODE"), ""+ voMapRequest.get("CONTACT_CITY_CODE"));
				    	vaDistrict = voAddressDAO.getDistrictName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"), ""+ voMapRequest.get("CONTACT_DISTRICT_CODE"));
				    	vaProvince = voAddressDAO.getProvinceName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"));
				    	vaPostCode = ""+ voMapRequest.get("CONTACT_POST_CODE");
				    	vaTelephone = "" + voMapRequest.get("CONTACT_TELEPHONE");
				    	vaRequestDescription = ""+ voMapRequest.get("DESCRIPTION");
				    	
				    	voObject.put("requestNumber", vaRequestNumber);
						voObject.put("applicantName", vaApplicantName);
						voObject.put("homeNumber", vaHomeNumber);
						voObject.put("address", vaAddress);
						voObject.put("city", vaCity);
						voObject.put("district", vaDistrict);
						voObject.put("province", vaProvince);
						voObject.put("postCode", vaPostCode);
						voObject.put("telephone", vaTelephone);
						voObject.put("requestDescription", vaRequestDescription);
						voObject.put("receiveCode", voReceiveCode);
						voObject.put("description", voDescription);
						voObject.put("receiveAmount", voReceiveAmount);
			    	}
				}
			} else {
				if (voArrayList.size() != 0 && voMapRequest.get("STATUS").toString().equals("2")) {
		    		voObject.put("message", "resultNull");
		    	}else{

					vaRequestGroup = ""+ voMapRequest.get("REQUEST_GROUP");
					vaRequestType = ""+ voMapRequest.get("REQUEST_TYPE");
					if (vaRequestGroup.equals("0")) {
						
							voArrayList = voRequestQuoteDAO.searchRequestQuote(vnSiteId, vaInputRequestNumber);
//							if (voArrayList.size() == 0) {
//					    		voObject.put("message", "resultNull");
//					    	} else {
					    		for (int i = 0; i < voArrayList.size(); i++) {
					    			voMapRequestQuote = voArrayList.get(i);	
					    			voReceiveCode.add(voMapRequestQuote.get("RECEIVE_CODE"));
									voDescription.add(voMapRequestQuote.get("DESCRIPTION"));
									voReceiveAmount.add(voMapRequestQuote.get("RECEIVE_AMOUNT"));
								}
					    		
					    		vaRequestNumber = ""+ voMapRequest.get("REQUEST_NUMBER");
						    	vaApplicantName = ""+ voMapRequest.get("APPLICANT_NAME");
						    	vaHomeNumber = ""+ voMapRequest.get("CONTACT_HOME_NUMBER");
						    	vaAddress = "" + voMapRequest.get("CONTACT_ADDRESS");
						    	vaCity = voAddressDAO.getCityName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"), ""+ voMapRequest.get("CONTACT_DISTRICT_CODE"), ""+ voMapRequest.get("CONTACT_CITY_CODE"));
						    	vaDistrict = voAddressDAO.getDistrictName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"), ""+ voMapRequest.get("CONTACT_DISTRICT_CODE"));
						    	vaProvince = voAddressDAO.getProvinceName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"));
						    	vaPostCode = ""+ voMapRequest.get("CONTACT_POST_CODE");
						    	vaTelephone = "" + voMapRequest.get("CONTACT_TELEPHONE");
						    	vaRequestDescription = ""+ voMapRequest.get("DESCRIPTION");
						    	
						    	voObject.put("requestNumber", vaRequestNumber);
								voObject.put("applicantName", vaApplicantName);
								voObject.put("homeNumber", vaHomeNumber);
								voObject.put("address", vaAddress);
								voObject.put("city", vaCity);
								voObject.put("district", vaDistrict);
								voObject.put("province", vaProvince);
								voObject.put("postCode", vaPostCode);
								voObject.put("telephone", vaTelephone);
								voObject.put("requestDescription", vaRequestDescription);
								voObject.put("receiveCode", voReceiveCode);
								voObject.put("description", voDescription);
								voObject.put("receiveAmount", voReceiveAmount);
//					    	}
						
					} else {
						voArrayList = voRequestQuoteDAO.searchRequestQuote(vnSiteId, vaInputRequestNumber);
//						if (voArrayList.size() == 0) {
//				    		voObject.put("message", "resultNull");
//				    	} else {
				    		for (int i = 0; i < voArrayList.size(); i++) {
				    			voMapRequestQuote = voArrayList.get(i);	
				    			voReceiveCode.add(voMapRequestQuote.get("RECEIVE_CODE"));
								voDescription.add(voMapRequestQuote.get("DESCRIPTION"));
								voReceiveAmount.add(voMapRequestQuote.get("RECEIVE_AMOUNT"));
							}
				    		
				    		vaRequestNumber = ""+ voMapRequest.get("REQUEST_NUMBER");
					    	vaApplicantName = ""+ voMapRequest.get("APPLICANT_NAME");
					    	vaHomeNumber = ""+ voMapRequest.get("CONTACT_HOME_NUMBER");
					    	vaAddress = "" + voMapRequest.get("CONTACT_ADDRESS");
					    	vaCity = voAddressDAO.getCityName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"), ""+ voMapRequest.get("CONTACT_DISTRICT_CODE"), ""+ voMapRequest.get("CONTACT_CITY_CODE"));
					    	vaDistrict = voAddressDAO.getDistrictName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"), ""+ voMapRequest.get("CONTACT_DISTRICT_CODE"));
					    	vaProvince = voAddressDAO.getProvinceName(""+ voMapRequest.get("CONTACT_PROVINCE_CODE"));
					    	vaPostCode = ""+ voMapRequest.get("CONTACT_POST_CODE");
					    	vaTelephone = "" + voMapRequest.get("CONTACT_TELEPHONE");
					    	vaRequestDescription = ""+ voMapRequest.get("DESCRIPTION");
					    	
					    	voObject.put("requestNumber", vaRequestNumber);
							voObject.put("applicantName", vaApplicantName);
							voObject.put("homeNumber", vaHomeNumber);
							voObject.put("address", vaAddress);
							voObject.put("city", vaCity);
							voObject.put("district", vaDistrict);
							voObject.put("province", vaProvince);
							voObject.put("postCode", vaPostCode);
							voObject.put("telephone", vaTelephone);
							voObject.put("requestDescription", vaRequestDescription);
							voObject.put("receiveCode", voReceiveCode);
							voObject.put("description", voDescription);
							voObject.put("receiveAmount", voReceiveAmount);
//				    	}
					}
		    	}
			}
		}
		db.close();
    	voOut.print(voObject.toJSONString());
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
